package com.ruoyi.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.ReReport;
import com.ruoyi.service.IReReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 业务报告控制器
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/biz/report")
public class BizReportController extends BaseController {
    @Autowired
    private IReReportService reReportService;


    /**
     * 测试接口
     */
    @GetMapping("/test")
    @PreAuthorize("permitAll()")
    public AjaxResult test() {
        try {
            return success("业务报告控制器正常工作");
        } catch (Exception e) {
            logger.error("测试接口异常", e);
            return error("测试失败：" + e.getMessage());
        }
    }

    /**
     * 插入蓝牙数据报告
     */
    @Log(title = "蓝牙数据报告", businessType = BusinessType.INSERT)
    @PostMapping("/insertReport")
    @PreAuthorize("permitAll()")
    public AjaxResult insertReport(@RequestBody ReReport reReport) {
        try {
            logger.info("接收到蓝牙数据报告请求，设备MAC: {}, 设备ID: {}",
                    reReport.getDeviceMac(), reReport.getDeviceId());

            // 验证必要字段
            if (reReport.getDeviceMac() == null || reReport.getDeviceMac().isEmpty()) {
                return error("设备MAC地址不能为空");
            }
            if (reReport.getDeviceId() == null || reReport.getDeviceId().isEmpty()) {
                return error("设备ID不能为空");
            }
            if (reReport.getHexs() == null || reReport.getHexs().isEmpty()) {
                return error("蓝牙数据不能为空");
            }

            // 处理hexs数据格式
            String hexs = reReport.getHexs();
            if (!hexs.startsWith("[") && hexs.contains(",")) {
                // 如果是逗号分隔的格式，转换为JSON数组格式存储
                String[] hexArray = hexs.split(",");
                String jsonHexs = "[" + String.join(",",
                        java.util.Arrays.stream(hexArray)
                                .map(hex -> "\"" + hex.trim() + "\"")
                                .toArray(String[]::new))
                        + "]";
                reReport.setHexs(jsonHexs);
                logger.info("转换后的hexs格式: {}", jsonHexs.substring(0, Math.min(100, jsonHexs.length())) + "...");
            }

            // 设置默认值
            if (reReport.getReportNum() == null || reReport.getReportNum().isEmpty()) {
                // reReport.setReportNum("YG-01");
                reReport.setReportNum("");
            }
            if (reReport.getArrTimestamp() == null || reReport.getArrTimestamp().isEmpty()) {
                reReport.setArrTimestamp(String.valueOf(System.currentTimeMillis()));
            }

            // 设置创建者信息 - 对于匿名请求使用默认值
            try {
                reReport.setCreateBy(getUsername());
            } catch (Exception e) {
                // 如果是匿名请求，使用默认值
                // reReport.setCreateBy("anonymous");
                reReport.setCreateBy("");
                logger.info("使用匿名用户作为创建者");
            }

            // 调用服务层插入数据
            int result = reReportService.insertReReport(reReport);

            if (result > 0) {
                logger.info("蓝牙数据报告保存成功，ID: {}", reReport.getId());
                return success("数据保存成功");
            } else {
                logger.error("蓝牙数据报告保存失败，返回结果: {}", result);
                return error("数据保存失败");
            }
        } catch (Exception e) {
            logger.error("保存蓝牙数据报告失败", e);
            return error("数据保存失败：" + e.getMessage());
        }
    }
}
